package myrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * MySpringCloud
 *
 * @Title: com.hrp.MyRule
 * @Date: 2020/5/23 18:52
 * @Author: wfg
 * @Description:原来是纯随机策略 我们现在改为。
 * 如果一个下标已经被随机到了2次了，第三次还是同样的下标的话，那就再随机一次
 * @Version:
 */
public class MyRule extends AbstractLoadBalancerRule {

    private Random rand;
    private int lastIndex = -1;
    private int nowIndex = -1;
    private int skipIndex = -1;

    public MyRule() {
        rand = new Random();
    }


    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while (server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();
                List<Server> allList = lb.getAllServers();

                System.out.println("allList:" + lb.getAllServers());
                System.out.println("upList:" + lb.getReachableServers());

                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

                int index = this.chooseRandomInt(serverCount);


                System.out.println("当前下标为:" + index);
                if (skipIndex >= 0 && index == skipIndex) {
                    System.out.println("跳过");
                    index = rand.nextInt(serverCount);
                    System.out.println("跳过后的下标:" + index);
                }
                skipIndex = -1;

                nowIndex = index;
                if (nowIndex == lastIndex) {
                    System.out.println("下一次需要跳过的下标" + nowIndex);
                    skipIndex = nowIndex;
                }
                lastIndex = nowIndex;


                server = (Server) upList.get(index);
                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    @Override
    public Server choose(Object key) {
        System.out.println("key:"+key);
        return this.choose(this.getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}

